package com.rfid.afd.activity;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AnimationUtils;
import android.view.animation.LayoutAnimationController;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.rfid.afd.activity.view.ICommonUiView;
import com.rfid.afd.activity.view.IView;
import com.rfid.afd.presenter.BasePresenter;
import com.rfid.afd.presenter.BaseUiPresenter;
import com.rfid.db.bean.Deleted;
import com.rfid.db.bean.Operation;
import com.rfid.db.bean.Rfid;
import com.rfid.rls_psw.R;
import com.rfid.util.DBManager;
import com.rfid.util.LogUtils;
import com.rfid.util.SearchManager;
import com.rfid.util.Util;
import com.rfid.widget.LoadingView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public abstract class BaseCommonUiActivity<T extends BaseUiPresenter> extends BaseActivity<T> implements ICommonUiView {

    @BindView(R.id.recyclerview)
    RecyclerView mRecyclerView;
    @BindView(R.id.rfid)
    TextView mShelfTextView;
    protected List<Rfid>mAdapterData;
    protected Map<String,Rfid> mUidIndex;//记录扫描到的rfid信息。
    private MyAdapter myAdapter;
    boolean isStarted;
    protected String mShelf;
    @BindView(R.id.complete)
    Button mComplete;
    @BindView(R.id.back)
    Button mBackButton;
    @BindView(R.id.rescan)
    Button mRescanButton;
    @BindView(R.id.check)
    TextView mCheck;
    @BindView(R.id.errshelf)
    TextView mErrShelf;
    @BindView(R.id.edit)
    EditText mEditText;
    @BindView(R.id.edit_confirm)
    Button mEditConfirm;
    @BindView(R.id.total)
    TextView mTotal;
    @BindView(R.id.check_title)
    TextView mCheckTitle;
    int count;
    int errCount;

    private List<Rfid> mDeleteds;
    private boolean isDataLoaded;

    @BindView(R.id.loading)
    LoadingView mLoadingView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_checkbook_layout);
//        mData = new ArrayList<>();
        mAdapterData = new ArrayList<>();
        mUidIndex = new HashMap<String,Rfid>();
        ButterKnife.bind(this);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mRecyclerView.addItemDecoration(new DividerItemDecoration(this,RecyclerView.VERTICAL));
        myAdapter = getAdapter();
        mRecyclerView.setAdapter(myAdapter);
        LayoutAnimationController controller = new LayoutAnimationController(AnimationUtils.loadAnimation(this,android.R.anim.fade_in));
        mRecyclerView.setLayoutAnimation(controller);
        mShelfTextView.setText("请扫描层标");
        mEditText.setVisibility(View.GONE);
        mErrShelf.setText("0");
        mDeleteds = new ArrayList<>();

        mPresenter.queryDeleteRfids();
        mRescanButton.setEnabled(false);
        mComplete.setEnabled(false);
    }

    protected MyAdapter getAdapter() {
        return new BaseCommonUiActivity.MyAdapter(mAdapterData);
    }

    @Override
    public void onScaned(String epc, Rfid rfid) {
        System.out.println(rfid);
        if(TextUtils.isEmpty(mShelf) || !isDataLoaded) {
            return;
        }
        if(mUidIndex.containsKey(epc)) {
            Rfid r = mUidIndex.get(epc);
            int flag = r.getFlag();
            if(flag != 0) {
                return;
            }
            count++;
            r.setFlag(Rfid.FLAG_CHECKED);
            if(SearchManager.getInstance().getSearchRfids().contains(r)) {
                r.setFlag(Rfid.FLAG_FIND|Rfid.FLAG_CHECKED);
            } else {
                mAdapterData.remove(r);
            }
            freshListUi();
            mCheck.setText(count + "");
        } else {
//            if(mDeleteds.contains(rfid)) {//服务器要求删除的，并且错架了;暂时不管后台的删除
//                mUidIndex.put(epc,rfid);
////                mData.add(0,rfid);
//                mAdapterData.add(0,rfid);
//                freshListUi();
//                return;
//            }
            rfid.setFlag(Rfid.FLAG_ERR_SHELF);
            if(SearchManager.getInstance().getSearchRfids().contains(rfid)) {
                rfid.setFlag(Rfid.FLAG_FIND|Rfid.FLAG_ERR_SHELF);
            }
            mUidIndex.put(epc,rfid);
            mAdapterData.add(0,rfid);
            if(rfid.getId() == null) {
                freshListUi();
                return;
            }
            errCount++;
//            mData.add(0,rfid);
            onErrorShelf(rfid);
            freshListUi();
            mErrShelf.setText(errCount + "");
        }
        mComplete.setEnabled(true);
    }

    @OnClick(R.id.edit_confirm)
    public void onClick(View view) {
        if(view == mEditConfirm) {
            boolean v = mEditText.getVisibility() != View.VISIBLE;
            switchEdit(v);
        }
    }

    private void switchEdit(boolean v) {
        if(!v) {
            mEditText.setVisibility(View.GONE);
            mShelfTextView.setVisibility(View.VISIBLE);
            mEditConfirm.setText("编辑");
            String shelf = mEditText.getText().toString();
            if(!TextUtils.isEmpty(shelf)) {
                String os = mShelfTextView.getText().toString();
                System.out.println("os = " + os + ",shelf = " + shelf);
                if(!shelf.equals(os))
                    onShelf(shelf);
            } else {
                mShelfTextView.setText("请扫描层标");
            }
        } else {
            mEditConfirm.setText("保存");
            mShelfTextView.setVisibility(View.GONE);
            mEditText.setVisibility(View.VISIBLE);
//                String shelf = mShelfTextView.getText().toString();
//                if(TextUtils.isEmpty(shelf) || Util.isContainChinese(shelf)) {
//                    return;
//                }
//                mEditText.setText(mShelfTextView.getText());
        }
    }

    public void onDeleteQuery(List<Rfid> deletes) {
        mDeleteds.clear();;
        mDeleteds.addAll(deletes);
        for(Rfid rfid : mDeleteds) {
            rfid.setFlag(Rfid.FLAG_DELETE);
        }
    }

    @Override
    public synchronized void onShelf(String shelf) {
//        if(!TextUtils.isEmpty(mShelf) || TextUtils.isEmpty(shelf)) {
//            return;
//        }
        mShelf = shelf;
        mPresenter.setDisableShelf(true);
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
//                scan(findViewById(R.id.scan),false);
                mRescanButton.setEnabled(true);
                mShelfTextView.setText("" + mShelf);
                mEditText.setText(mShelf);
                mEditConfirm.setEnabled(false);
                onShelfGot(shelf);
            }
        });
    }

    protected void onShelfGot(String shelf) {
    }

    @Override
    public void finish() {
        super.finish();
//        mPresenter.updateOperation();
    }

    @Override
    public void showLoading() {
        System.out.println("showLoading");
        mLoadingView.setVisibility(View.VISIBLE);
    }

    @Override
    public void stopLoading() {
        mLoadingView.setVisibility(View.GONE);
    }

    protected void onErrorShelf(Rfid rfid) {
    }

    public void start(View v) {
        scan((TextView) v,!isStarted);
    }

    private void scan(TextView v, boolean b) {
        TextView button = v;
        if(!b) {
            button.setText("开始");
            mBackButton.setEnabled(true);
            mPresenter.stopScanRfid();
            if (TextUtils.isEmpty(mShelf)) {
                mEditConfirm.setEnabled(true);
            }
        } else {
            button.setText("暂停");
            mBackButton.setEnabled(false);
            mPresenter.startScanRfid();
            mEditConfirm.setEnabled(false);
        }
        isStarted = b;
    }

    public void complete(View v) {
        scan(findViewById(R.id.scan),false);
        isDataLoaded = false;
        mUidIndex.clear();
        mAdapterData.clear();
        myAdapter.notifyDataSetChanged();
        mShelfTextView.setText("请扫描层标");
        mEditText.setText("");
        switchEdit(false);
        mErrShelf.setText("");
        mCheck.setText("");
        mShelf = null;
        mPresenter.setDisableShelf(false);
        mPresenter.updateOperation();
        mComplete.setEnabled(false);
        mRescanButton.setEnabled(false);
        mEditConfirm.setEnabled(true);
    }

    public void rescan(View view) {
        scan(findViewById(R.id.scan),false);
        isDataLoaded = false;
        mUidIndex.clear();
        mAdapterData.clear();
        myAdapter.notifyDataSetChanged();
        mShelfTextView.setText("请扫描层标");
        mEditText.setText("");
        switchEdit(false);
        mErrShelf.setText("");
        mCheck.setText("");
        mShelf = null;
        mPresenter.setDisableShelf(false);
        mComplete.setEnabled(false);
        mRescanButton.setEnabled(false);
        mEditConfirm.setEnabled(true);
    }

    public synchronized void updateData(List<Rfid> data) {
        System.out.println("updateData");
//        mData.clear();
        mUidIndex.clear();
        errCount = 0;
//        mData.addAll(data);
        for(int i=0;i<data.size();i++) {
            mUidIndex.put(data.get(i).getUid(),data.get(i));
        }
        mAdapterData.clear();
        myAdapter.notifyDataSetChanged();
        mAdapterData.addAll(data);
        myAdapter.notifyDataSetChanged();
//        mCheck.setText("0/" + mUidIndex.size());
        mTotal.setText("" + mUidIndex.size());
        isDataLoaded = true;
    }

    protected void freshListUi() {
        myAdapter.notifyDataSetChanged();
    }

    public void back(View view) {
        onBackPressed();
    }

    @Override
    public void onBackPressed() {
        LogUtils.v("onBackPressed");
        if(isStarted) {
            return;
        }
        super.onBackPressed();
        mPresenter.stopScanRfid();
//        for(Rfid rfid : mData) {
//            rfid.setFlag(0);
//        }
        Set<Map.Entry<String, Rfid>> entries =  mUidIndex.entrySet();
        Iterator<Map.Entry<String, Rfid>> it = entries.iterator();
        while(it.hasNext()) {
            System.out.println("next");
            it.next().getValue().setFlag(Rfid.FLAG_OK);
        }
//        mPresenter.updateOperation();
    }



    public class MyAdapter extends RecyclerView.Adapter<BaseCommonUiActivity.MyAdapter.MyViewHolder> {

        private List<Rfid> mRfids;

        public MyAdapter(List<Rfid> data) {
            mRfids = data;
        }

        @NonNull
        @Override
        public BaseCommonUiActivity.MyAdapter.MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            return new BaseCommonUiActivity.MyAdapter.MyViewHolder(getLayoutInflater().inflate(R.layout.item_base_common_ui_layout,parent,false));
        }

        @Override
        public void onBindViewHolder(@NonNull BaseCommonUiActivity.MyAdapter.MyViewHolder holder, int position) {
            Rfid rfid = mRfids.get(position);
            holder.id.setText((position + 1) + "");
            if(rfid.getId() != null) {
                holder.name.setText(rfid.getBookName());
                holder.index.setText(rfid.getRindex());
                holder.shelf.setText(rfid.getShelf());
                LogUtils.v("rfid.getFlag() = " + rfid.getFlag());
                if ((rfid.getFlag() & Rfid.FLAG_ERR_SHELF) == Rfid.FLAG_ERR_SHELF) {
                    holder.itemView.setBackgroundColor(Color.RED);
                    LogUtils.v("shelf = " + rfid.getShelf() + ",origin = " + rfid.getOriginShelf());
                    holder.shelf.setText(rfid.getOriginShelf() + "");
                } else if (rfid.getFlag() == Rfid.FLAG_DELETE) {//服务器要求剔除，暂时不开发了。
                    holder.itemView.setBackgroundColor(Color.YELLOW);
                } else {
                    holder.itemView.setBackgroundColor(Color.WHITE);
                }
                if ((rfid.getFlag() & Rfid.FLAG_FIND) == Rfid.FLAG_FIND) {
                    holder.icon.setImageResource(R.mipmap.find);
                } else {
                    holder.icon.setImageResource(0);
                }
            } else {
                holder.itemView.setBackgroundColor(Color.YELLOW);
                holder.name.setText("");
                holder.index.setText("");
                holder.shelf.setText("");
            }
            holder.barcode.setText(rfid.getBarcode());
            holder.epc.setText(rfid.getUid());
        }

        @Override
        public int getItemCount() {
            return mRfids.size();
        }

        class MyViewHolder extends RecyclerView.ViewHolder {
            @BindView(R.id.book_name)
            TextView name;
            @BindView(R.id.barcode)
            TextView barcode;
            @BindView(R.id.index)
            TextView index;
            @BindView(R.id.shelf)
            TextView shelf;
            @BindView(R.id.icon)
            ImageView icon;
            @BindView(R.id.id)
            TextView id;
            @BindView(R.id.epc)
            TextView epc;
            public MyViewHolder(@NonNull View itemView) {
                super(itemView);
                ButterKnife.bind(this,itemView);
            }
        }
    }
}